package com.qing.eduservice.controller.front;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qing.eduservice.entity.pojo.EduComment;
import com.qing.eduservice.service.EduCommentService;
import com.qing.servicebase.exception.JsonException;
import com.qing.servicebase.utils.JwtUtils;
import com.qing.servicebase.utils.ResponseResult;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName Yjx
 * @Description TODO
 * @date 2022/9/18 19:48
 * @Version 1.0
 */
@RestController
@RequestMapping("/eduservice/comment")
@CrossOrigin
public class CommentFrontController {

    private final EduCommentService commentService;

    public CommentFrontController(EduCommentService commentService) {
        this.commentService = commentService;
    }

    //根据课程id查询评论列表
    @GetMapping("/{page}/{pageSize}")
    public ResponseResult index(@PathVariable("page") int page, @PathVariable("pageSize") int pageSize, String courseId) {
        Page<EduComment> pageParam = new Page<>(page, pageSize);
        QueryWrapper<EduComment> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        commentService.page(pageParam,wrapper);
        List<EduComment> commentList = pageParam.getRecords();
        Map<String, Object> map = new HashMap<>();
        map.put("items", commentList);
        map.put("current", pageParam.getCurrent());
        map.put("pages", pageParam.getPages());
        map.put("size", pageParam.getSize());
        map.put("total", pageParam.getTotal());
        map.put("hasNext", pageParam.hasNext());
        map.put("hasPrevious", pageParam.hasPrevious());
        return ResponseResult.ofSuccess(map);
    }

    @PostMapping("/auth/save")
    public ResponseResult save(@RequestBody EduComment comment, HttpServletRequest request) {
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if(StringUtils.isEmpty(memberId)) {
            return ResponseResult.ofException(new JsonException(201,"操作失败"));
        }
        comment.setMemberId(memberId);
        commentService.save(comment);
        return ResponseResult.ofSuccess("评论成功");
    }
}
